package com.x.mvp.utils;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

public abstract class GlobalDialog {
    private static final int MESSAGE_TIMEOUT = 2;
    private WindowManager wdm;
    private double time;
    private View mView;
    private WindowManager.LayoutParams params;
    private WorkerHandler mHandler;
    private boolean isShow = false;

    public GlobalDialog(Context context, double time) {
        wdm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        mHandler = new WorkerHandler();

        Toast toast = Toast.makeText(context, "", Toast.LENGTH_LONG);
        mView = createView(context);
        params = new WindowManager.LayoutParams();
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.format = PixelFormat.TRANSLUCENT;
        params.windowAnimations = toast.getView().getAnimation().INFINITE;
        params.type = WindowManager.LayoutParams.TYPE_TOAST;
        params.setTitle("Toast");
        params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
        params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;

        this.time = time;
    }

    protected abstract View createView(Context context);

    protected abstract void onCancel();

    public void show(int t) {
        time = t != 0 ? t : time;
        wdm.addView(mView, params);
        isShow = true;
        mHandler.sendEmptyMessageDelayed(MESSAGE_TIMEOUT, (long) (time * 1000));
    }

    public void cancel() {
        wdm.removeView(mView);
        isShow = false;
        onCancel();
    }

    public boolean isShow() {
        return isShow;
    }

    private class WorkerHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_TIMEOUT:
                    cancel();
                    break;
            }
        }
    }
}
